package controllers;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import models.*;
import play.Logger;
import play.db.jpa.GenericModel;
import play.db.jpa.JPA;
import play.db.jpa.JPABase;
import play.db.jpa.Model;
import play.mvc.Controller;

import javax.persistence.PrePersist;
import javax.persistence.Query;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.*;

/**
 * User: bicho
 * Date: 25/07/12 15:14
 * Email: bichocj@gmail.com
 */
public class Eventos extends Controller {

    public static void index() {
        String limit = params.get("limit");
        String start = params.get("start");
        String page = params.get("page");
        String end = params.get("end");
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
        List<Evento> eventos = Evento.findAll();
        renderJSON(gson.toJson(eventos));
    }

//    public static void create(String a) {
//        String body = params.data.get("body")[0];
//        Evento evento =
//
//        response.status = 201;
//        response.print(tarea.id);
//    }


//    public static void update(Long id, String a) {
//        String body = params.data.get("body")[0];
//        Tarea tarea = getTareaFromBody(body);
//        tarea.save();
//        renderJSON("success");
//    }

//    public static void get(Long id) {
//        Tarea tarea = Tarea.findById(id);
//        renderJSON(tarea);
//    }

//    public static void delete(Long id) {
//        Tarea tarea = Tarea.findById(id);
//        tarea.delete();
//        response.status = 204;
//    }


//    private static Evento getEventoFromBody(String body) {
//        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
//        Tarea tarea= gson.fromJson(body, Tarea.class);
//        tarea= JPA.em().merge(tarea);
//        return tarea;
//    }


    public static void byHembra(Long hembraId) {
//      TODO update to use JQL
        Query query = JPA.em().createNativeQuery("select e.*, t.nombre as 'tipo_evento',t.dependencia1,  t.dependencia2, t.tarea from evento e join tipo_evento t " +
                "on e.tipo_evento_id = t.id where e.porcino_id =" + hembraId, EventoDto.class);
        List<EventoDto> eventos = query.getResultList();
        List<EventoDto> eventosMapper = new ArrayList<EventoDto>();
        for (EventoDto eventoDto : eventos) {
            if (!eventoDto.isTarea) {
                for (EventoDto evento2Dto : eventos) {
                    if (eventoDto.id == evento2Dto.dependencia) {
                        if (eventoDto.children == null) {
                            eventoDto.children = new ArrayList<EventoDto>();
                        }
                        evento2Dto.leaf = true;
                        eventoDto.children.add(evento2Dto);
                    }
                }

                if (eventoDto.children == null) {
                    eventoDto.leaf = true;
                }
                eventosMapper.add(eventoDto);
            }
        }


        Map<String, Object> map = new HashMap<String, Object>();
        map.put("text", ".");
        map.put("children", eventosMapper);

        renderJSON(map);

    }

    public static void byEvento(Long eventoId) {
        Evento evento = Evento.findById(eventoId);
        PcModel model = null;
        int tipoEventoId = Integer.parseInt(evento.tipoEventoId.toString());
        switch (tipoEventoId) {
            case 1:
                model = EventoMontaNatural.findById(evento.id);
                break;
            case 2:
                model = EventoParto.findById(evento.id);
                break;
            default:
                model = new PcModel();
        }

        Field[] fields = model.getClass().getFields();
        List<Map> objects = new ArrayList<Map>();
        try {
            for (Field field : fields) {
                Map<String, Object> map = new HashMap<String, Object>();
                if (!field.getName().equals("willBeSaved") & !field.getName().equals("id")) {
                    StringBuilder stringBuilder = new StringBuilder(field.getName());
                    map.put("valor", field.get(model));
                    map.put("propiedad", stringBuilder.replace(0, 1, stringBuilder.substring(0, 1).toUpperCase()).toString());
                    objects.add(map);
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        renderJSON(objects);
    }

    public static void save(String a) {
        String body = params.data.get("body")[0];
        body = body.replaceAll("T00:00:00", "");
        Gson gson = new GsonBuilder().setDateFormat("MM/dd/yyyy").create();

        Evento evento = gson.fromJson(body, Evento.class);
        TipoEvento tipoEvento = TipoEvento.findById(evento.tipoEventoId);
        Porcino porcino = Porcino.findById(evento.porcinoId);

        evento = JPA.em().merge(evento);
        evento.tipoEventoId = tipoEvento.getId();
        evento.fechaFin = evento.fechaInicio;
        evento.titulo = porcino.codigo + ", " + tipoEvento.nombre;


        PcModel model = null;
        int tipoEventoId = Integer.parseInt(tipoEvento.id.toString());
        switch (tipoEventoId) {
            case 1:
                model = gson.fromJson(body, EventoMontaNatural.class);
                break;
            case 2:
                model = gson.fromJson(body, EventoParto.class);
                break;
            case 3:
                model = gson.fromJson(body, EventoCeloNoServido.class);
                break;
            case 4:
                model = gson.fromJson(body, EventoDestete.class);
                break;
            case 5:
                model = gson.fromJson(body, EventoAdopcion.class);
                break;
            case 6:
                model = gson.fromJson(body, EventoInseminacion.class);
                break;
        }
        evento.descripcion = model.getDescripcion();
        evento.save();

        model.id = evento.getId();
        model = JPA.em().merge(model);
        model.save();

        List<TipoEvento> tipoEventos = TipoEvento.find("( tarea = true or tareaEvento = true ) and ( dependencia1 = ? or dependencia2 = ?)", tipoEventoId, tipoEventoId).fetch();

        EventoDto eventoDto = EventoDto.parse(evento, tipoEvento.nombre, false);

        for (TipoEvento tareaEvento : tipoEventos) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(evento.fechaInicio);

            Evento eventoTarea = new Evento();
            eventoTarea.dependencia = evento.id;
            eventoTarea.porcinoId = evento.porcinoId;
            eventoTarea.tipoEventoId = tareaEvento.id;
            eventoTarea.titulo = porcino.codigo + ", " + tareaEvento.nombre;
            calendar.add(Calendar.DATE, tareaEvento.dias);
            eventoTarea.fechaInicio = calendar.getTime();
//            calendar.add(Calendar.DATE, 1);
            eventoTarea.fechaFin = calendar.getTime();
            eventoTarea.save();

            if (eventoDto.children == null) {
                eventoDto.children = new ArrayList<EventoDto>();
            }

            eventoDto.children.add(EventoDto.parse(eventoTarea, tareaEvento.nombre, true));
        }


        renderJSON(eventoDto);
    }
}
